package xyz.jiang.file.controller;

import cn.hutool.core.util.IdUtil;
import io.minio.ObjectWriteResponse;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import xyz.jiang.common.grace.result.GraceJSONResult;
import xyz.jiang.common.pojo.dto.PresignFileDTO;
import xyz.jiang.common.utils.UserUtils;
import xyz.jiang.file.config.MinIOConfig;
import xyz.jiang.file.openfeign.api.UserApiClient;
import xyz.jiang.file.utils.MinIOUtils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@RequestMapping("/minio")
@RestController
public class FileController {

    @Resource
    private MinIOConfig minIOConfig;

    @Resource
    private UserApiClient userApiClient;

    @PostMapping("/uploadAvatarFile")
    public GraceJSONResult uploadFile(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws Exception {

        String userId = UserUtils.getUserId();

        String fileName = file.getOriginalFilename();
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        //生成文件名称uuid
        String uuid = IdUtil.simpleUUID();;
        String datePath = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        String newFileName =  datePath + "/" + uuid +suffixName;
        ObjectWriteResponse objectWriteResponse = MinIOUtils.uploadFile(minIOConfig.getBucketName(), newFileName, file.getInputStream());

        String faceUrl = minIOConfig.getFileHost() + "/" + minIOConfig.getBucketName() + "/" + newFileName;
        GraceJSONResult graceJSONResult = userApiClient.uploadFile(faceUrl);
        System.out.println(graceJSONResult);
        return GraceJSONResult.ok(faceUrl);
    }

    @PostMapping("/presignUrl")
    public GraceJSONResult presignUrl(@RequestBody PresignFileDTO presignFileDTO) throws Exception {
        String filename = presignFileDTO.getFilename();
        String objectName = UUID.randomUUID() + "-" + filename;
        String url = MinIOUtils.getPresignedObjectUrl("wechat", objectName);
        System.out.println(url);
        return GraceJSONResult.ok(url);
    }
}
